//
//  LifeViewController.m
//  ProjectB
//
//  Created by lanou on 16/5/5.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "LifeViewController.h"
#import "YYCoreDataHandler.h"
#import "ClockView.h"
#import "PortraitsViewController.h"
#import "AppDelegate.h"
#import <SVProgressHUD.h>
#import "RecordTableViewController.h"

@interface LifeViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *timeImageView;
@property (strong, nonatomic) IBOutletCollection(UIView) NSArray *lifeViews;
@property (weak, nonatomic) IBOutlet UIView *lifeView;
@property (weak, nonatomic) IBOutlet UILabel *aLabel;
@property (weak, nonatomic) IBOutlet UIButton *shareButton;
@property (weak, nonatomic) IBOutlet UIStackView *stackViewOne;
@property (weak, nonatomic) IBOutlet UIStackView *stackViewTwo;
@property (weak, nonatomic) IBOutlet UILabel *yearLabel;
@property (weak, nonatomic) IBOutlet UILabel *monthLabel;
@property (weak, nonatomic) IBOutlet UILabel *weekLabel;
@property (weak, nonatomic) IBOutlet UILabel *dayLabel;
@property (weak, nonatomic) IBOutlet UILabel *hourLabel;
@property (weak, nonatomic) IBOutlet UILabel *mintueLabel;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *ageLabels;
@property (nonatomic, strong) ClockView *clockView;
@property (nonatomic, strong) UIBarButtonItem *headItem;
@property (nonatomic, strong) UIBarButtonItem *wishItem;
@property (nonatomic, strong) UIBarButtonItem *menuItem;
@property (nonatomic, strong) UITextField *nameTF;
@property (nonatomic, strong) UILabel *bLabel;
@property (nonatomic, strong) UIView *pickerView;
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation LifeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"white"] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"currentUser"] || [[YYCoreDataHandler sharedCoreDataHandler] selectObjectByKey:[[NSUserDefaults standardUserDefaults] objectForKey:@"currentUser"]].count == 0) {
        [self startLifeWithAnimation:NO];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (self.deadTimeButton.tag == 2222) {
        self.clockView.date = [NSDate date];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.extendedLayoutIncludesOpaqueBars = YES;
//    self.navigationController.navigationBar.translucent = NO;
    
    _headItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"headB"] style:UIBarButtonItemStylePlain target:self action:@selector(goHead)];
    _wishItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"wishB"] style:UIBarButtonItemStylePlain target:self action:@selector(goWish)];
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:self.wishItem, self.headItem, nil];
    
    for (UIView *v in self.lifeViews) {
        v.layer.borderWidth = 1;
        v.layer.borderColor = [UIColor grayColor].CGColor;
    }
    
    self.deadTimeButton.layer.cornerRadius = 15;
    self.deadTimeButton.layer.borderWidth = 1;
    self.deadTimeButton.layer.borderColor = [UIColor grayColor].CGColor;
    self.deadTimeButton.tag = 2222;
    
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"currentUser"] || [[YYCoreDataHandler sharedCoreDataHandler] selectObjectByKey:[[NSUserDefaults standardUserDefaults] objectForKey:@"currentUser"]].count == 0) {
        [self startLifeWithAnimation:NO];
        return;
    }

    [self showData];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}

- (void)endLifeWithBlock:(id)block {
    [UIView animateWithDuration:0.5 animations:^{
        self.stackViewOne.alpha = 1;
        self.stackViewTwo.alpha = 1;
        self.lifeView.alpha = 1;
        self.aLabel.alpha = 1;
        self.shareButton.alpha = 1;
        self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:self.wishItem, self.headItem, nil];
        self.navigationItem.leftBarButtonItem = self.menuItem;
        
        self.clockView.transform = CGAffineTransformMakeTranslation(0, 0);
        
        [self.deadTimeButton setTitle:@"死之钟" forState:UIControlStateNormal];
        self.deadTimeButton.tag = 2222;
        self.deadTimeButton.transform = CGAffineTransformMakeTranslation(0, 0);
        
        self.nameTF.alpha = 0;
        
        self.nameTF.userInteractionEnabled = NO;
        
        self.bLabel.alpha = 0;
    } completion:^(BOOL finished) {
        if (block && ![block isMemberOfClass:[UIBarButtonItem class]]) {
            ((void(^)())block)();
        }
        
        self.clockView.date = [NSDate date];
        self.clockView.autoRun = YES;
    }];
}

- (void)startLifeWithAnimation:(BOOL)animation {
    float duration = 0;
    self.clockView.autoRun = NO;
    self.clockView.minute = 0;
    self.clockView.hour = 0;
    [self.clockView setFirstSecond:0];
    
    if (animation) {
        duration = 0.5;
        UIBarButtonItem *endItem = [UIBarButtonItem createBackImageItem];
        endItem.target = self;
        endItem.action = @selector(endLifeWithBlock:);
        if (!self.menuItem) {
            self.menuItem = self.navigationItem.leftBarButtonItem;
        }
        self.navigationItem.leftBarButtonItem = endItem;
    } else {
        if (!self.menuItem) {
            self.menuItem = self.navigationItem.leftBarButtonItem;
        }
        self.navigationItem.leftBarButtonItem = nil;
    }
    
    [UIView animateWithDuration:duration animations:^{
        self.stackViewOne.alpha = 0;
        self.stackViewTwo.alpha = 0;
        self.lifeView.alpha = 0;
        self.aLabel.alpha = 0;
        self.shareButton.alpha = 0;
        self.navigationItem.rightBarButtonItems = nil;
        
        if (!self.clockView) {
            _clockView = [[ClockView alloc] initWithFrame:self.timeImageView.bounds hour:0 minute:0 second:0 autoRun:YES];
            self.clockView.autoRun = NO;
            self.clockView.center = CGPointMake(self.timeImageView.width / 2, self.timeImageView.height / 2);
            [self.timeImageView addSubview:self.clockView];
        }
        self.clockView.transform = CGAffineTransformMakeTranslation(0, 30);
        
        [self.deadTimeButton setTitle:@"选择日期" forState:UIControlStateNormal];
        self.deadTimeButton.tag = 4444;
        self.deadTimeButton.transform = CGAffineTransformMakeTranslation(0, -30);
        
        if (self.nameTF) {
            self.nameTF.alpha = 1;
            if (animation) {
                User *user = [[YYCoreDataHandler sharedCoreDataHandler] selectObjectByKey:[[NSUserDefaults standardUserDefaults] objectForKey:@"currentUser"]].firstObject;
                [self createDatePicker];
                self.nameTF.enabled = NO;
                self.nameTF.text = user.name;
                self.datePicker.date = user.birthday;
            } else {
                self.nameTF.enabled = YES;
                self.nameTF.text = nil;
                self.datePicker.date = [NSDate dateWithTimeIntervalSince1970:666666666];
            }
        } else {
            self.nameTF = [[UITextField alloc] initWithFrame:CGRectMake(100, self.timeImageView.y + 30 + self.timeImageView.height + 20, kScreenWidth - 200, 21)];
            self.nameTF.textAlignment = NSTextAlignmentCenter;
            self.nameTF.placeholder = @"你的名字";
            if (animation) {
                User *user = [[YYCoreDataHandler sharedCoreDataHandler] selectObjectByKey:[[NSUserDefaults standardUserDefaults] objectForKey:@"currentUser"]].firstObject;
                [self createDatePicker];
                self.nameTF.enabled = NO;
                self.nameTF.text = user.name;
                self.datePicker.date = user.birthday;
            } else {
                self.nameTF.enabled = YES;
                self.nameTF.text = @"";
                self.datePicker.date = [NSDate dateWithTimeIntervalSince1970:666666666];
            }
            [self.view addSubview:self.nameTF];
        }
        self.nameTF.userInteractionEnabled = YES;
        
        if (self.bLabel) {
            self.bLabel.alpha = 1;
        } else {
            self.bLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth / 2 - 8.5,self.timeImageView.y +  30 + self.timeImageView.height + 20 + 21 + 10, 17, 21 * 3)];
            self.bLabel.numberOfLines = 3;
            self.bLabel.text = @"出生于";
            [self.view addSubview:self.bLabel];
        }
    }];
}

- (void)showData {
    NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentUser"];
    User *user = [[YYCoreDataHandler sharedCoreDataHandler] selectObjectByKey:username].firstObject;
    NSArray *lifeTime = [user getLifeTime];
    
    NSString *ageStr = [lifeTime objectAtIndex:6];
    for (int i = 0; i < 11; i++) {
        ((UILabel *)[self.ageLabels objectAtIndex:i]).text = [@"0" stringByAppendingString:[ageStr substringWithRange:NSMakeRange(i, 1)]];
    }
    
    self.yearLabel.text = [lifeTime objectAtIndex:0];
    self.monthLabel.text = [lifeTime objectAtIndex:1];
    self.weekLabel.text = [lifeTime objectAtIndex:2];
    self.dayLabel.text = [lifeTime objectAtIndex:3];
    self.hourLabel.text = [lifeTime objectAtIndex:4];
    self.mintueLabel.text = [lifeTime objectAtIndex:5];
    
    if (!self.clockView) {
        _clockView = [[ClockView alloc] initWithFrame:self.timeImageView.bounds hour:0 minute:0 second:0 autoRun:YES];
        self.clockView.center = CGPointMake(self.timeImageView.width / 2, self.timeImageView.height / 2);
        [self.timeImageView addSubview:self.clockView];
    }
    
    if (!self.timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeAge) userInfo:nil repeats:YES];
    }
}

- (void)changeAge {
    NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentUser"];
    User *user = [[YYCoreDataHandler sharedCoreDataHandler] selectObjectByKey:username].firstObject;
    NSArray *lifeTime = [user getLifeTime];
    
    NSString *ageStr = [lifeTime objectAtIndex:6];
    
    for (int i = 0; i < 11; i++) {
        UILabel *ageLabel = [self.ageLabels objectAtIndex:i];
        NSString *ageS = [ageStr substringWithRange:NSMakeRange(i, 1)];
        if (![ageS isEqualToString:[ageLabel.text substringFromIndex:1]]) {
            [UIView animateWithDuration:0.2 animations:^{
                ageLabel.text = [NSString stringWithFormat:@"%@%@", ageS, [ageLabel.text substringFromIndex:1]];
                ageLabel.transform = CGAffineTransformMakeTranslation(0, ageLabel.frame.size.height / 2);
            } completion:^(BOOL finished) {
                ageLabel.text = [NSString stringWithFormat:@"0%@", ageS];
                ageLabel.transform = CGAffineTransformMakeTranslation(0, 0);
            }];
        }
    }
    
    self.yearLabel.text = [lifeTime objectAtIndex:0];
    self.monthLabel.text = [lifeTime objectAtIndex:1];
    self.weekLabel.text = [lifeTime objectAtIndex:2];
    self.dayLabel.text = [lifeTime objectAtIndex:3];
    self.hourLabel.text = [lifeTime objectAtIndex:4];
    self.mintueLabel.text = [lifeTime objectAtIndex:5];
    
}

- (void)goHead {
    PortraitsViewController *portraitsVC = [[PortraitsViewController alloc] init];
    [self.navigationController pushViewController:portraitsVC animated:YES];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    self.navigationController.navigationBar.tintColor = nil;
}

- (void)goWish {
    RecordTableViewController *recordTVC = [[RecordTableViewController alloc] init];
    [self.navigationController pushViewController:recordTVC animated:YES];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    self.navigationController.navigationBar.tintColor = nil;
}

- (IBAction)share:(UIButton *)sender {
    NSLog(@"share");
}

- (void)createDatePicker {
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    if (!self.backgroundView) {
        _backgroundView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _backgroundView.backgroundColor = [UIColor blackColor];
        [delegate.window addSubview:_backgroundView];
        self.backgroundView.alpha = 0.5;
        self.backgroundView.hidden = YES;
    }
    
    if (!self.pickerView) {
        _pickerView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, 250)];
        _pickerView.backgroundColor = [UIColor whiteColor];
        [delegate.window addSubview:_pickerView];
        
        UIButton *cancel = [UIButton buttonWithType:UIButtonTypeSystem];
        cancel.frame = CGRectMake(0, 0, 40, 30);
        [cancel setTitle:@"取消" forState:UIControlStateNormal];
        cancel.tintColor = [UIColor blackColor];
        [cancel addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
        [_pickerView addSubview:cancel];
        
        UIButton *confirm = [UIButton buttonWithType:UIButtonTypeSystem];
        confirm.frame = CGRectMake(kScreenWidth - 40, 0, 40, 30);
        [confirm setTitle:@"完成" forState:UIControlStateNormal];
        confirm.tintColor = [UIColor blackColor];
        [confirm addTarget:self action:@selector(confirm) forControlEvents:UIControlEventTouchUpInside];
        [_pickerView addSubview:confirm];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, kScreenWidth - 80, 30)];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"选择出生日期";
        [_pickerView addSubview:label];
        
        if (!self.datePicker) {
            _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 30, kScreenWidth, 220)];
            _datePicker.datePickerMode = UIDatePickerModeDate;
            _datePicker.date = [NSDate dateWithTimeIntervalSince1970:666666666];
            _datePicker.maximumDate = [NSDate date];
            _datePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:-3000000000];
            [_pickerView addSubview:_datePicker];
        }
    }
}

- (void)showDatePicker {
    self.backgroundView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        self.pickerView.transform = CGAffineTransformMakeTranslation(0, -250);
    }];
}

- (void)confirm {
    if ([self.nameTF.text isEqualToString:@""]) {
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请输入你的名字" message:nil preferredStyle:UIAlertControllerStyleAlert];
//        [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:nil]];
//        [self.navigationController presentViewController:alert animated:YES completion:nil];
        
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请输入你的名字" message:nil delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil];
//        [alert show];
        
        [SVProgressHUD showErrorWithStatus:@"请输入你的名字"];
    } else {
        User *user = [YYCoreDataHandler getNewManagedObject];
        user.name = self.nameTF.text;
        user.birthday = self.datePicker.date;
        if (![[YYCoreDataHandler sharedCoreDataHandler] insertObject:user]) {
            [[YYCoreDataHandler sharedCoreDataHandler] updateObjectByKey:user.name withDictionary:[NSDictionary dictionaryWithObjectsAndKeys:user.birthday, @"birthday", @(-1), @"maxAge", nil]];
        }
        
        [[NSUserDefaults standardUserDefaults] setObject:user.name forKey:@"currentUser"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        self.changeUserBlock();
        [self cancel];
        [self endLifeWithBlock:^{
            self.clockView.date = [NSDate date];
            self.clockView.autoRun = YES;
        }];
        [self showData];
    }
}

- (void)cancel {
    self.backgroundView.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        self.pickerView.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}

- (IBAction)deadTimeButtonAction:(UIButton *)sender {
    if (sender.tag == 4444) {
        [self createDatePicker];
        [self showDatePicker];
    } else if (sender.tag == 2222) {
        self.deadBlock();
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
